<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="vhtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, defineModel, watch, readonly } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IEditorConfig } from '@wangeditor/editor'
import comFunc from '@/common/comFunc'
import { uploadFileStream } from '@/api/file'

type InsertFnType = (url: string, alt: string, href: string) => void

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  }
})

const vhtml = ref('<p></p>')
const model = defineModel({ type: String })

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const mode = ref('default')

// 模拟 ajax 异步获取内容
onMounted(() => {
  setHtmlValue(model.value)
})

const toolbarConfig = {}
const percentage = ref(0)
// 初始化 MENU_CONF 属性
const editorConfig: Partial<IEditorConfig> = {
  // TS 语法
  // const editorConfig = {                       // JS 语法
  MENU_CONF: {
    uploadImage: {
      async customUpload(file: File, insertFn: InsertFnType) {
        // TS 语法
        // async customUpload(file, insertFn) {                   // JS 语法
        // file 即选中的文件
        // 自己实现上传，并得到图片 url alt href
        // 最后插入图片
        percentage.value = 0
        const re = await uploadFileStream(file, (per) => {
          percentage.value = per
        })
        console.log(re)
        if (re.isSuccess) {
          insertFn(re.remotePath ? re.remotePath : '', '', re.path ? re.path : '')
        }
      }
    }
  },
  placeholder: '请输入内容...'
}
editorConfig.readOnly = props.disabled
watch(
  () => model.value,
  (val) => {
    setHtmlValue(val)
  }
)
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleChange = (editor) => {
  model.value = vhtml.value
}
const setHtmlValue = (v: string | undefined) => {
  if (!v) {
    vhtml.value = '<p></p>'
    return
  }
  if (comFunc.nvl(v) === '') {
    vhtml.value = '<p></p>'
  } else {
    vhtml.value = v
  }
}
</script>
<style lang="scss" scoped></style>
